<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\BBillsModel;
use App\Model\OrdersModel;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class OrdersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrdersModel::query();
        $query->when(checkIsHasField($params,'orders_id'),function ($query)use ($params){
            $query->where('orders_id',$params['orders_id']);
        });

        $query->when(checkIsHasField($params,'orders_code'),function ($query)use ($params){
            $query->where('orders_code',$params['orders_code']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });
        $query->when(checkIsHasField($params,'shop_id'),function ($query)use ($params){
            $query->where('shop_id',$params['shop_id']);
        });
        return $query->orderByDesc('created_at');
    }
    public static function orders($params = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        if(getShopId()){
            $params['shop_id'] = getShopId();
        }
        return self::builder_query($params)->paginate();
    }

    public static function orders_info($params = []): array
    {
        return self::builder_query($params)->first()->toArray();
    }


    /**
     * @desc 订单下单
     * @param array $params
     * @return array
     * @throws SysExceptions
     */
    public static function orders_create(array $params = [])
    {
        checkForData(['user_id','nums','goods_id','address_id'],['用户不正确','请选择数量','请选择商品','请选择地址'],$params);
//        checkForData(['user_id','goods_id','address_id','pay_pass'],['用户不正确','请选择商品','请选择地址','请输入支付密码'],$params);
        //检测用户支付密码
//        UsersDao::check_pass($params['pay_pass'],$params['user_id']);
        $address_query = AddressDao::get_address_builder_query(['address_id'=>$params['address_id']]);
        if(!$address_query->exists()){
            self::error('地址不存在');
        }
        $address_info = $address_query->first()->toArray();
        $goods_query = GoodsDao::builder_query(['goods_id'=>$params['goods_id'],'show'=>1]);
        if(!$goods_query->exists()){
            self::error('请选择正确的商品');
        }
        //商品信息
        $goods_info = $goods_query->first()->toArray();
        $price = $goods_info['goods_price']*$params['nums'];

        //获取用户信息
        $user_query = UsersDao::builder_query(['user_id'=>$params['user_id']]);
        if(!$user_query->exists()){
            self::error('用户不存在');
        }
        //用户信息

        $shopInfo = BusinessesDao::builder_query([
            'businesses_id'=>$goods_info['shop_id']
        ])->first()->toArray();
        $order_code = makeOrderNo();
        //创建订单
        $order_data = [
            'user_id'=>$params['user_id'],
            'status'=>0,
            'price'=>$price,
            'orders_code'=>$order_code,
            'goods_id'=>$params['goods_id'],
            'nums'=>$params['nums'],
            'address_id'=>$params['address_id'],
            'shop_id'=>$goods_info['shop_id'],
            'shop_info'=>json_encode($shopInfo,JSON_UNESCAPED_UNICODE),
            'address_json'=>json_encode($address_info,JSON_UNESCAPED_UNICODE),
            'orders_json_data'=>json_encode($goods_info,JSON_UNESCAPED_UNICODE),
        ];
        //创建订单并且扣费
        DB::beginTransaction();
        try {
            self::builder_query()->create($order_data);
//            BillsDao::moneysUpdate(-($order_data['price']),$order_data['user_id'],'购买商品扣费');
            $userInfo = UsersDao::builder_query(['user_id'=>$params['user_id']])->first()->toArray();
            $dataResult = PayServices::pay([
                'openid'=>$userInfo['openid'],
                'name'=>$shopInfo['businesses_title'],
                'price'=>$price,
                'order_code'=>$order_code,
                'notify_url'=>route('admin.notice_pay_price_order')
            ]);
            DB::commit();
            return $dataResult;
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function userUploadInfo(array $params)
    {
        //查询状态已经发货不允许修改
        checkForData(['orders_id','user_uplaod_info'],['请选择订单','请填写上传信息'],$params);
        $order_query = self::builder_query(['orders_id'=>$params['orders_id']]);
        if(!$order_query->exists()){
            self::error('订单不存在');
        }
        $orders_info = $order_query->first()->toArray();
        if($orders_info['status'] > 2){
            self::error('订单状态不正确!');
        }
        if(!$order_query->update([
            'user_uplaod_info' => json_encode($params['user_uplaod_info'], JSON_UNESCAPED_UNICODE),
            'status'=>2
        ])){
            self::error('订单修改失败!');
        }
    }

    /**
     * @desc 订单发货
     * @param array|null $params
     * @return void
     * @throws SysExceptions
     */
    public static function send_orders(array $params)
    {
        checkForData(['wuliu_num'],['请输入物流单号'],$params);
        $orders_query = self::builder_query(['orders_id'=>$params['orders_id']]);
        if(!$orders_query->exists()){
            self::error('订单不存在!');
        }
        $orders_info = $orders_query->first()->toArray();
        if($orders_info['status'] != 1){
            self::error('订单状态不正确!');
        }

        if (self::builder_query(['orders_id'=>self::deleteParamId($params,'orders_id')])->update(['wuliu_num'=>$params['wuliu_num'],'status'=>3]) === false){
            self::error('修改失败');
        }
    }

    public static function confirm(array $params)
    {
        //确认收货升级/返佣
        $orderQuery = self::builder_query([
            'orders_code'=>$params['orders_code']
        ]);
        //订单不存在
        if(!$orderQuery->exists()){
            self::error('订单不存在!');
        }
        //订单信息
        $orderInfo = $orderQuery->first()->toArray();

        if($orderInfo['status'] != 3){
            self::error('状态不正确');
        }
        //确认收货并且绑定
        DB::beginTransaction();
        try {
            //确认收货
            $orderQuery->update([
                'status'=>4
            ]);
            UsersDao::changePrices($orderInfo['price'],$orderInfo['user_id']);
            $orderInfo['shop_info'] = json_decode($orderInfo['shop_info'],JSON_UNESCAPED_UNICODE);
            //添加排队
            $ratePrice = bcmul($orderInfo['price'],(1-$orderInfo['shop_info']['rate']),2);
            if($ratePrice > 0){
                LineUpPriceDao::addCreate($ratePrice,$orderInfo['user_id'],$orderInfo['shop_id']);
            }
            //多少钱用于返费比例
            $rate_price_data = $orderInfo['shop_info']['rate_price_data'];
            $zongPrice = bcmul($orderInfo['price'],$rate_price_data,2);
            //订单给商家钱并且扣掉手续费
            $rateRP = bcmul($zongPrice,0.1,2);
            if($zongPrice > 0){
                SbillsDao::moneysUpdate($orderInfo['price'],$orderInfo['shop_id'],'收取费用到账');
                SbillsDao::moneysUpdate(-($zongPrice-$rateRP),$orderInfo['shop_id'],'扣除让利费用');
                SbillsDao::moneysUpdate(-($rateRP),$orderInfo['shop_id'],'扣除手续费');
                BusinessesDao::nowPrice(bcsub($zongPrice,$rateRP,2),$orderInfo['shop_id'],$orderInfo['shop_info']);
            }
            //进行升级或者返费
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            var_dump($exception->getMessage());
        }
    }

    public static function noticeOrder($out_trade_no)
    {
        $query = self::builder_query([
            'orders_code'=>$out_trade_no,
            'status'=>0
        ]);
        if(!$query->exists()){
            self::error('失败');
        }
        $orderInfo = $query->first()->toArray();
        $query->update([
            'status'=>1
        ]);
    }


}
